package com.vrv.netmgr.alarm.chart;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.common.UrlPrefix;
import com.vrv.common.util.HttpClientToServer;
import com.vrv.netmgr.R;

/**
 * 审计报警概况
 *
 * @author gaopei
 *
 */
@SuppressLint("HandlerLeak")
public class AlarmChartActivity extends Activity {

	/** 为统计图开辟的区域 */
	private LinearLayout layout;
	List<String> listLabel = new ArrayList<String>();
	List<Long> listVal = new ArrayList<Long>();
	/** 饼形图 */
	GraphicalView pieChartView = null;
	CategorySeries dataset;
	DefaultRenderer renderer;
	/**
	 * 等待对话框
	 */
	private ProgressDialog progressDialog;
	/**
	 * 查询
	 */
	private static final int QUERY_ALARM = 1;
	private static final int QUERY_AUDIT = 2;
	private static final int NET_ERR = 99;
	private String chartTitle;

	// PopWindow检索条件相关
	private ImageButton moreFuncBtn;
	private PopupWindow pwMyPopWindow;
	private ListView lvPopupList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.alarm_region_statistics_layout);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tools_title);

		initView();

		progressDialog = ProgressDialog.show(AlarmChartActivity.this, "", "查询中...", true, true);

		new Thread(new Runnable() {
			@Override
			public void run() {
				getDataFromServer(QUERY_ALARM);
				/** update by zxb 20130726 修改程序异常崩溃 */
				if (null == listVal || listVal.size() == 0) {
					return;
				}
				handler.sendEmptyMessage(QUERY_ALARM);
			}
		}).start();
	}

	/**
	 * 处理器
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
			case QUERY_ALARM:
				buildLineChartView(QUERY_ALARM);
				break;
			case QUERY_AUDIT:
				buildLineChartView(QUERY_AUDIT);
				break;
			case NET_ERR:
				Toast.makeText(AlarmChartActivity.this, "网络连接失败", Toast.LENGTH_LONG).show();
				break;
			}
		}
	};

	private void initView() {
		TextView title = (TextView) findViewById(R.id.title_text);
		title.setText("审计报警概况");
		// 返回按钮
		ImageButton backBtn = (ImageButton) findViewById(R.id.backBtn);
		backBtn.setVisibility(View.VISIBLE);
		backBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});

		// 初始化chart的渲染位置
		layout = (LinearLayout) findViewById(R.id.bar_chart);
		iniPopupWindow();
		// 更多操作按钮
		moreFuncBtn = (ImageButton) findViewById(R.id.moreFunctionBtn);
		moreFuncBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (pwMyPopWindow.isShowing()) {
					pwMyPopWindow.dismiss();// 关闭
				} else {
					pwMyPopWindow.showAsDropDown(moreFuncBtn);// 显示
				}
			}
		});
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void iniPopupWindow() {
		LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.title_func_popupwindow, null);
		lvPopupList = (ListView) layout.findViewById(R.id.lv_popup_list);
		pwMyPopWindow = new PopupWindow(layout);
		pwMyPopWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件

		String[] arr = getResources().getStringArray(R.array.alarmChartType);
		if (null == itemDatas) {
			itemDatas = new ArrayList();
		} else {
			itemDatas.clear();
		}
		for (int i = 0; i < arr.length; i++) {
			PopItem item = new PopItem();
			item.title = arr[i];
			item.check = false;
			if (0 == i) {
				item.check = true;
			}
			itemDatas.add(item);
		}
		if (null == pAdapter) {
			pAdapter = new PopWindowAdapter(itemDatas, AlarmChartActivity.this);
		}
		lvPopupList.setAdapter(pAdapter);
		lvPopupList.setOnItemClickListener(new ClickPopupItemListener());

		// 控制popupwindow的宽度和高度自适应
		lvPopupList.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
		pwMyPopWindow.setWidth(lvPopupList.getMeasuredWidth());
		// pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight()) * 3);
		pwMyPopWindow.setHeight(LayoutParams.WRAP_CONTENT);

		// 控制popupwindow点击屏幕其他地方消失
		pwMyPopWindow.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.bg_popupwindow));
		// 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功，如上
		pwMyPopWindow.setOutsideTouchable(true);
	}

	private class ClickPopupItemListener implements AdapterView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
			pwMyPopWindow.dismiss();

			progressDialog = ProgressDialog.show(AlarmChartActivity.this, "", "查询中...", true, true);

			new Thread(new Runnable() {
				@Override
				public void run() {
					int what = 0;
					switch (position) {
					case QUERY_ALARM - 1:
						what = QUERY_ALARM;
						break;
					case QUERY_AUDIT - 1:
						what = QUERY_AUDIT;
						break;
					}
					getDataFromServer(what);
					handler.sendEmptyMessage(what);
				}
			}).start();

			for (int i = 0; i < itemDatas.size(); i++) {
				if (position == i) {
					itemDatas.get(i).check = true;
				} else {
					itemDatas.get(i).check = false;
				}
			}
			pAdapter.notifyDataSetChanged();
//			Toast.makeText(AlarmChartActivity.this, "" + itemDatas.get(position).title, Toast.LENGTH_LONG).show();
		}
	}

	public List<PopItem> itemDatas;
	public PopWindowAdapter pAdapter;

	public class PopWindowAdapter extends BaseAdapter {
		public List<PopItem> lst;
		public Context mContext;

		public PopWindowAdapter(List<PopItem> lst, Context context) {
			this.lst = lst;
			this.mContext = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return lst.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return lst.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(AlarmChartActivity.this).inflate(R.layout.list_item_popupwindow, null);
			}
			CheckBox cBox = (CheckBox) convertView.findViewById(R.id.check);
			TextView title = (TextView) convertView.findViewById(R.id.tv_list_item);

			cBox.setChecked(lst.get(position).check);
			title.setText(lst.get(position).title);

			return convertView;
		}

	}

	public class PopItem {
		public String title;
		public boolean check = false;
	}

	@SuppressLint("SimpleDateFormat")
	public void buildLineChartView(int type) {
		/** update by zxb 20130726 修改程序异常崩溃 */
		if (null == listVal || listVal.size() == 0) {
			return;
		}

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String[] titles = null;
		if (type == QUERY_ALARM)
			titles = new String[] { "终端报警" };
		else if (type == QUERY_AUDIT)
			titles = new String[] { "终端审计" };
		List<Date[]> dates = new ArrayList<Date[]>();
		List<Object[]> values = new ArrayList<Object[]>();
		int length = titles.length;
		for (int i = 0; i < length; i++) {
			dates.add(new Date[7]);
			try {
				for (int j = 0; j < 7; j++)
					dates.get(i)[j] = formatter.parse(listLabel.get(j));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		values.add(listVal.toArray());
		length = values.get(0).length;
		int[] colors = new int[] { Color.BLUE };
		PointStyle[] styles = new PointStyle[] { PointStyle.POINT };
		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
		renderer.setChartTitle(chartTitle);
		renderer.setXTitle("日期");
		renderer.setYTitle("报警数量");
		renderer.setXAxisMin(dates.get(0)[0].getTime());
		renderer.setXAxisMax(dates.get(0)[6].getTime());
		renderer.setYAxisMin(0);
		// renderer.setYAxisMax(yMax);
		renderer.setAxesColor(Color.BLACK);
		renderer.setLabelsColor(Color.BLACK);
		renderer.setMargins(new int[] { 40, 40, 40, 40 });
		renderer.setXLabels(7);
		// renderer.setYLabels(6);
		renderer.setShowGrid(true);
		renderer.setXLabelsColor(Color.BLACK);
		renderer.setYLabelsColor(0, Color.BLACK);
		renderer.setXLabelsAngle(-10);
		//renderer.setXLabelsPadding(20);
		renderer.setMarginsColor(getResources().getColor(R.color.gray1));
		length = renderer.getSeriesRendererCount();
		for (int i = 0; i < length; i++) {
			SimpleSeriesRenderer seriesRenderer = renderer.getSeriesRendererAt(i);
			seriesRenderer.setDisplayChartValues(true);
		}
		if (pieChartView != null)
			layout.removeView(pieChartView);
		pieChartView = ChartFactory.getTimeChartView(this, buildDateDataset(titles, dates, values), renderer, "yyyy/MM/dd");
		layout.addView(pieChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}

	/**
	 * Builds an XY multiple time dataset using the provided values.
	 *
	 * @param titles
	 *            the series titles
	 * @param xValues
	 *            the values for the X axis
	 * @param yValues
	 *            the values for the Y axis
	 * @return the XY multiple time dataset
	 */
	protected XYMultipleSeriesDataset buildDateDataset(String[] titles, List<Date[]> xValues, List<Object[]> yValues) {
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		int length = titles.length;
		for (int i = 0; i < length; i++) {
			TimeSeries series = new TimeSeries(titles[i]);
			Date[] xV = xValues.get(i);
			Object[] yV = yValues.get(i);
			int seriesLength = xV.length;
			for (int k = 0; k < seriesLength; k++) {
				series.add(xV[k], (Long) yV[k]);
			}
			dataset.addSeries(series);
		}
		return dataset;
	}

	/**
	 * Builds an XY multiple series renderer.
	 *
	 * @param colors
	 *            the series rendering colors
	 * @param styles
	 *            the series point styles
	 * @return the XY multiple series renderers
	 */
	protected XYMultipleSeriesRenderer buildRenderer(int[] colors, PointStyle[] styles) {
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		renderer.setAxisTitleTextSize(20);
		renderer.setChartTitleTextSize(25);
		renderer.setLabelsTextSize(12);
		renderer.setLegendTextSize(20);
		renderer.setPointSize(15f);
		renderer.setLegendHeight(100);
		renderer.setMargins(new int[] { 20, 20, 100, 20});
		int length = colors.length;
		for (int i = 0; i < length; i++) {
			XYSeriesRenderer r = new XYSeriesRenderer();
			r.setColor(colors[i]);
			r.setPointStyle(styles[i]);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}

	public CategorySeries buildCategoryDataset(String title, Object[] labels, Object[] values) {
		CategorySeries series = new CategorySeries(title);
		int k = 0;
		for (Object value : values) {
			series.add((String) labels[k++], (Long) value);
		}
		return series;
	}

	public DefaultRenderer buildCategoryRenderer(int[] colors) {
		DefaultRenderer renderer = new DefaultRenderer();
		renderer.setLabelsTextSize(20);
		renderer.setLegendTextSize(20);
		renderer.setMargins(new int[] { 0, 30, 15, 0 });
		for (int i = 0; i < listLabel.size(); i++) {
			SimpleSeriesRenderer r = new SimpleSeriesRenderer();
			r.setColor(colors[i]);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}

	// 查询所有数据
	public void getDataFromServer(int statisticsType) {
		switch (statisticsType) {
		case QUERY_ALARM:
			chartTitle = "过去一周终端报警情况";
			break;
		case QUERY_AUDIT:
			chartTitle = "过去一周终端审计情况";
			break;
		}

		Map<String, String> map = new HashMap<String, String>();
		boolean retVal = qryRegisterStat(map, statisticsType);
		if (!retVal)
			handler.sendEmptyMessage(NET_ERR);
	}

	/**
	 * 查询服务器数据
	 *
	 * @param map
	 *            参数封装
	 * @param statisticsType
	 *            终端审计、终端报警类型判断
	 * @return
	 */
	public boolean qryRegisterStat(Map<String, String> map, int statisticsType) {
		boolean retVal = false;
		HttpClientToServer httpClientToServer = new HttpClientToServer();
		String urlPrefix = new UrlPrefix(getApplicationContext()).getUrlPrefix();
		String urlTailString = null;
		switch (statisticsType) {
		case QUERY_ALARM:
			urlTailString = "/errorMessage/getPastWeekErrorInfo.do";
			break;
		case QUERY_AUDIT:
			urlTailString = "/pmoveableDiskEvent/getPastWeekAuditInfo.do";
			break;
		}
		String urlAddr = urlPrefix + urlTailString;
		String response = httpClientToServer.doPost(urlAddr, map);

		if (HttpClientToServer.DO_POST_ERR.equals(response) || HttpClientToServer.DO_POST_EXCEPT.equals(response))
			return retVal;

		try {
			JSONTokener jsonParser = new JSONTokener(response);
			JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
			retVal = jsonObj.getBoolean("success");
			if (!retVal)
				return retVal;
			int count = jsonObj.getInt("totalRecords");
			if (count < 1)
				return retVal;
			JSONArray jArr = jsonObj.getJSONArray("records");
			listLabel.clear();
			listVal.clear();
			for (int i = jArr.length() - 1; i >= 0; i--) {
				JSONObject jObj = (JSONObject) jArr.opt(i);
				getFieldsVal(jObj);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return retVal;
	}

	public void getFieldsVal(JSONObject jObj) {
		try {
			Iterator<?> iter = jObj.keys();
			String pastDate = iter.next().toString();
			listLabel.add(pastDate);
			listVal.add(jObj.getLong(pastDate));
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onBackPressed() {
		finish();
		overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
	}

	@Override
	protected void onResume() {
		super.onResume();
		initView();
	}
}
